import * as spritejs from 'spritejs'
const { Scene, Sprite, Polyline, Rect, Label } = spritejs

interface Door extends InstanceType<typeof Polyline> {
    open?: () => Promise<any>
    opened?: boolean
    close?: () => Promise<any>
    checkoutOpen?: () => Promise<any>
}

// 入口边框
export const enterPolyline = new Polyline({
    pos: [300, 100],
    points: [
        [0, 0],
        [-200, 0],
        [-200, 100],
        [0, 100],
    ],
    lineWidth: 1,
    strokeColor: '#000',
})

// 出口边框
export const leavePolyline = new Polyline({
    pos: [500, 0],
    points: [
        [0, 0],
        [0, 100],
        [-200, 100],
    ],
    lineWidth: 1,
    strokeColor: '#000',
    // fillColor: '#fff',
})

// 大门
export let enterDoor: Door | null = null
export let leaveDoor: Door | null = null
// 画出入口和出口
export const drawEnterAndLeave = function (layer) {
    // 入口文字
    const enterText = new Label({
        pos: [200, 150],
        text: '入口',
        font: '18px Arial',
        fillColor: '#000',
        anchor: [0.5, 0.5],
    })

    // 出口文字
    const leaveText = new Label({
        pos: [400, 50],
        text: '出口',
        font: '18px Arial',
        fillColor: '#000',
        anchor: [0.5, 0.5],
    })

    // 入口门
    enterDoor = new Polyline({
        points: [
            [0, 0],
            [0, 100],
        ],
        pos: [300, 100],
        lineWidth: 5,
        strokeColor: '#409eff',
        anchor: [0.5, 0],
        // fillColor: '#fff',
    })

    // 提供开门和关门的方法
    enterDoor.open = async () => {
        enterDoor.opened = true
        return enterDoor.transition(1).attr('rotate', -90)
    }
    enterDoor.close = async () => {
        enterDoor.opened = false
        return enterDoor.transition(1).attr('rotate', 0)
    }
    enterDoor.checkoutOpen = async () => {
        if (!enterDoor.opened) {
            return enterDoor.open()
        } else {
            return enterDoor.close()
        }
    }

    // 出口门
    leaveDoor = new Polyline({
        points: [
            [0, 0],
            [0, 100],
        ],
        pos: [300, 0],
        lineWidth: 5,
        strokeColor: '#409eff',
        anchor: [0.5, 0],
        // fillColor: '#fff',
    })

    // 提供开门和关门的方法
    leaveDoor.open = async () => {
        leaveDoor.opened = true
        return leaveDoor.transition(1).attr('rotate', 90)
    }
    leaveDoor.close = async () => {
        leaveDoor.opened = false
        return leaveDoor.transition(1).attr('rotate', 0)
    }
    leaveDoor.checkoutOpen = async () => {
        if (!leaveDoor.opened) {
            return leaveDoor.open()
        } else {
            return leaveDoor.close()
        }
    }

    layer.append(
        enterPolyline,
        enterText,
        leavePolyline,
        leaveText,
        leaveDoor,
        enterDoor
    )
}
